/**
 * 
 */
package io.dora.invoker;

import io.dora.base.Protocol;
import io.dora.base.ServiceInvoker;
import io.dora.remoting.ConsumerClient;
import io.dora.rpc.RpcInvocationHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Proxy;


/**
 * 默认调用器实现
 * 
 * @author zhaohongbo
 *
 */
public class DoraInvoker<T> implements ServiceInvoker<T> {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	/** 服务接口 */
	private Class<T> clazz;
	
	/** 服务唯一标识 */
	private String serviceKey;
	
	/** 服务提供方信息IP+Port */
	private String serviceHost;
	
	/** 协议 */
	private Protocol protocol;
	
	
	public DoraInvoker(Class<T> clazz, String serviceKey, Protocol protocol, String serviceHost) {
		this.clazz = clazz;
		this.serviceKey = serviceKey;
		this.protocol = protocol;
		this.serviceHost = serviceHost;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T invoke() {
		T obj = (T) Proxy.newProxyInstance(
				Thread.currentThread().getContextClassLoader(), 
				new Class[] { clazz },
				new RpcInvocationHandler(serviceKey, getAvailableClient()));
		return obj;
	}
	
	public ConsumerClient getAvailableClient() {
		logger.info("Get available:{} {}", serviceHost,  protocol.getConsumerClientMap());
		return protocol.getConsumerClientMap().get(serviceHost);
	}

}
